// pages/directBuy/directBuy.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    radioItems: [
      { name: '2', value: '在线支付', checked: 'true' },
    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // console.log( wx.getStorageSync('cartLists'))
    var cartLists = wx.getStorageSync('directCarts');//从本地缓存获取购物车的商品信息
    if (cartLists == "" || isNaN(cartLists[0].totalPrices)) {//判断购物车是否有东西，没有就显示没有，有就显示有的|
      this.setData({//隐藏信息
        hasCarts: true,
        noCarts: false
      })
    } else {//如果购物车有物品就遍历他，在把价格算出来
      this.setData({//显示信息
        hasCarts: false,
        noCarts: true
      })
      for (var y in cartLists) {//遍历购物车
        cartLists[y].totalPrices = parseFloat(cartLists[y].unitPrice * cartLists[y].quantity).toFixed(2)//让购物车里的单价乘以数量，得到单件商品的总价
      }
      this.setData({ cartLists: cartLists });//同步显示到页面
      wx.setStorageSync('directCarts', cartLists)//同步储存在本地以备购买时调用
      var totalMoneyArr = [];
      for (var index in this.data.cartLists) {//计算总的价格
        totalMoneyArr.push(parseFloat(this.data.cartLists[index].quantity * this.data.cartLists[index].unitPrice).toFixed(2));
      }
      var totalMoney = totalMoneyArr.reduce(function (a, b) {
        return (parseFloat(a) + parseFloat(b)).toFixed(2);
      });
      this.setData({
        totalMoney: (parseFloat(totalMoney)).toFixed(2),
      })

      wx.setStorageSync('totalMoney', that.data.totalMoney)//储存在本地以备购买时调用
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (wx.getStorageSync('checkboxchooseaddress')) {
      var checkboxaddress = wx.getStorageSync('checkboxchooseaddress');
     // console.log(checkboxaddress)
      this.setData({
        inputAddress: checkboxaddress.locationadd + checkboxaddress.expressageadd,
        inputPhone: checkboxaddress.phone,
        inputUser: checkboxaddress.consignee,
        directAddressId: checkboxaddress.id
      })
    } else {
      this.changeSuper()//加载该用户的地址
    }
    var that = this;

    wx.getSystemInfo({//获取滑块的高宽
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
  addQuantity: function (e) {//增加单个商品数量
    this.changeCartItemQuantity('+', e)
  },

  minusQuantity: function (e) {//减少单个商品数量
    this.changeCartItemQuantity('-', e)
  },

  changeCartItemQuantity: function (op, e) {//改变单个商品数量
    var that = this;
    var cartLists = this.data.cartLists//找到储存在本地购物车的商品信息
    var cart = cartLists.filter(function (ele) {//过滤出点击加减的商品在本地储存的唯一商品ID
      return ele.productId === e.currentTarget.dataset.id

    })[0]
    if (op === '-' && cart.quantity > 1) {//如果符号为－，则商品数量减一
      cart.quantity -= 1;
      cart.totalPrices = parseFloat(cart.quantity * cart.unitPrice).toFixed(2)
    } else if (op === '+') {//如果符号为+，则商品数量加一
      if (cart.quantity == cart.repertory) {//如果增加的数量大于库存，则取消增加；
        wx.showToast({
          title: "库存不足",
          icon: "loading"
        })
      } else {
        cart.quantity += 1;
      }
      cart.totalPrices = parseFloat(cart.quantity * cart.unitPrice).toFixed(2)
    } else if (op === '-' && cart.quantity == 1) {
      cart.quantity -= 1;
      cart.totalPrices = parseFloat(cart.quantity * cart.unitPrice).toFixed(2);
      //  console.log(cart);
    }
    for (var quantity in cartLists) {//移除购物车中数量为0的对象
      if (cartLists[quantity].quantity == 0) {
        cartLists.splice(quantity, 1)
      }
    }
    this.setData({ cartLists: cartLists })//同时将所修改的数量保存到当前页面的购物车中
    //  console.log(cartLists)
    wx.setStorageSync('directCarts', cartLists);
    if (cartLists != "") {//当购物车不为空的时候，在计算总金额
      var totalMoneyArr = [];
      for (var index in this.data.cartLists) {
        totalMoneyArr.push(parseFloat(this.data.cartLists[index].quantity * this.data.cartLists[index].unitPrice).toFixed(2));
      }
      var totalMoney = totalMoneyArr.reduce(function (a, b) {
        return (parseFloat(a) + parseFloat(b)).toFixed(2);
      });
      that.setData({
        totalMoney: totalMoney
      });
    } else {
      wx.setStorageSync('directCarts', "");
      that.setData({
        hasCarts: true,
        noCarts: false
      })
    }
  },
  changeSuper: function () {//获取该用户以前的超市地址
    var that = this;
    wx.request({
      url: app.globalData.allUrl + "/YMGW/addressAction/getAllAddress",
      data: {
        userID: wx.getStorageSync('userid')
      },
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function (res) {
        if (res.data) {
          that.setData({//如果有地址，则显示在页面上
            inputAddress: res.data[0].locationAdd + res.data[0].expressageAdd,
            inputPhone: res.data[0].phone,
            inputUser: res.data[0].consignee,
            directAddressId: res.data[0].id
          })
        }
        var items1 = [];
        for (var x in res.data) {
          // items1.unshift({ name: res.data[x].latitudeNum + " " + res.data[x].longitudeNum, value: res.data[x].expressageAdd });
          items1.unshift({ name: res.data[x].superId, value: res.data[x].expressageAdd });
        }

        that.setData({
          items: items1,
        })
      }
    })
    this.setData({
      chooseAddress: false
    })
  },

  getCartInfo: function () {//将用户购买的商品以及用户信息发送到后台生成预支付订单
    //console.log(this.data.inputUser)
    if (!this.data.inputUser) {
      wx.showModal({
        title: '检测到您暂无收货地址',
        content: '请点击确认到新增收货地址页面',
        showCancel: true,
        success: function (res) {
          if (res.confirm) {
            // determination = true;
            wx.navigateTo({
              url: '../addAddress/addAddress?direct=1',
            })
          }
        }
      })
    } else {
      var directDetail = wx.getStorageSync('directCarts')
     // console.log(directDetail)
      var detailJson = [];
      var that = this;
      if (directDetail) {
        for (var i = 0; i < directDetail.length; i++) {
          detailJson.push({
            shopsId: directDetail[i].directId,
            directId: directDetail[i].productId,
            totalPrices: directDetail[i].totalPrices,
            quantity: directDetail[i].quantity,
            unitPrice: directDetail[i].unitPrice,
          })
        }
      }
      //console.log(detailJson)
      wx.request({
        url: app.globalData.allUrl + "/YMGW/directWCPayAction/WeChatPayDirect",
        data: {
          userID: wx.getStorageSync('userid'),
          detailsjson: detailJson,
          totalMoney: that.data.totalMoney,
          addressID: that.data.directAddressId
        },
        method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        // header: {}, // 设置请求的 header
        success: function (res) {
          //console.log(res.data)
          // success
          if (res.data.packages) {
            var pay = res.data;
            wx.requestPayment({//如果从后台获取支付信息成功。则调用微信支付接口
              timeStamp: pay.timeStamp,
              nonceStr: pay.nonceStr,
              package: pay.packages,
              signType: pay.signType,
              paySign: pay.paySign,
              success: function (res) {
                // success
                //  console.log(res)
                wx.showToast({
                  title: '微信支付成功',
                  icon: 'success',
                  duration: 2000
                })
                wx.setStorageSync('directCarts', '')
                setTimeout(function () {//两秒后跳转到我的页面
                  wx.switchTab({
                    url: '../my/my',
                    success: function (res) {
                      // success
                    }
                  })
                }, 2000)
              }, fail(res) { }
            })

          }
        }
      })
    }

  },
})